/**
 * Created by Administrator on 2017/4/21.
 */
let mem = require('../util/mem.js');

let msg = module.exports;
let client;

msg.setLink = function (c) {
    client = c;
};
msg.addLink = function (cid, c) {
    mem.clients[cid] = c;
};
msg.send = function (cid, uuid, action, obj) {
    if (mem.clients[cid] == null) {
        return false;
    }
    if (mem.clients[cid].destroyed) {
        delete mem.clients[cid];
        return false;
    }
    let data = {};
    data.uuid = uuid;
    data.action = action;
    data.obj = obj;
    msg.write(mem.clients[cid], data);
    //mem.clients[cid].write(JSON.stringify(data) + '||');
};
msg.broadcast = function (uuid, action, obj) {
    for (let i in mem.clients) {
        if (mem.clients[i].destroyed) {
            delete mem.clients[i];
            return false;
        }
        let data = {};
        data.uuid = uuid;
        data.action = action;
        data.obj = obj;
        msg.write(mem.clients[i], data);
        //mem.clients[i].write(JSON.stringify(data) + '||');
    }
};
msg.carry = function (c, uuid, action, userId, data) {
    if (c == null) {
        return false;
    }
    let obj = {};
    obj.uuid = uuid;
    obj.userId = userId;
    obj.action = action;
    obj.data = data;
    msg.write(c, obj);
    //c.write(JSON.stringify(obj) + '||');
};
msg.write = function (c, obj) {
    c.write(JSON.stringify(obj) + '||');
    return false;
    //let buf = new Buffer(JSON.stringify(obj));
    //let buf = new Buffer(JSON.stringify(obj) + '||');

    //let str;
    //try {
    //    str = JSON.stringify(obj);
    //} catch (e) {
    //    console.error(e, obj);
    //}
    //let buf1 = new Buffer(str);
    //let buf2 = new Buffer(2);
    //buf2.writeInt16BE(buf1.length, 0);
    //let buf = Buffer.concat([buf2, buf1]);
    //c.write(buf);
};